<?php if(empty($__vue_upload_mixin)): ?>
<!--  防止重复渲染，加入一个判断条件 -->
<?php $__vue_upload_mixin=true; ?>
<script type="text/x-template" id="uploading-file-list">
    <div class="uploading_file_list">
        <el-dialog
                :model-value="show"
                title="文件上传"
                width="500px"
                @close="$emit('close')"
        >
            <div>
                <div v-for="(item,index) in lists" :key="index" style="margin-bottom: 10px;">
                    <div>
                        {{item.file_name}}
                    </div>
                    <div style="margin-top: 4px">
                        <el-progress
                                :text-inside="true"
                                :stroke-width="16"
                                :percentage="item.percent"
                                status="success"
                        />
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="$emit('close')">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</script>
<script>
    component_list.push({
        key: 'uploading-file-list',
        c: {
            template: `#uploading-file-list`,
            props: {
                lists: [Array, Object],
                show: Boolean,
            },
            computed: {
                finished() {
                    let is_finished = false
                    let has_false = false
                    for (let key in this.lists) {
                        let item = this.lists[key]
                        if (item.percent < 100) {
                            has_false = true
                        }
                    }
                    if (!has_false) {
                        is_finished = true
                    }
                    return is_finished
                }
            },
            watch: {
                show(value) {
                    if (value) {
                        this.finishClose()
                    }
                }
            },
            data() {
                return {}
            },
            mounted() {
            },
            methods: {
                finishClose() {
                    setTimeout(() => {
                        if (this.finished) {
                            this.$emit('close')
                        } else {
                            this.finishClose()
                        }
                    }, 1000)
                }
            }
        }
    });
</script>

<script>
    window.__vue_upload_mixin = {
        data() {
            return {
                show_uploading: false,
                uploading_file_list: [],
                upload_drive: '',
                move_group_id: -1,
                upload_url: "{:url('component/upload/file')}",
                group_list: [],
                now_group: -1,
                form_data: {},
                upload_setting: {},
                acl: 'default',
                is_init: false,
            }
        },
        props: {
            show: Boolean,
            public_read: Boolean,
        },
        watch: {
            show(value) {
                if (value && !this.is_init) {
                    this.getGroupList()
                    this.is_init = true
                }
            }
        },
        mounted() {

        },
        computed: {
            selected_file_ids() {
                let selected_file_ids = []
                this.selected_file_list.forEach(file => {
                    selected_file_ids.push(file.file_id)
                })
                return selected_file_ids
            },
            selected_file_list() {
                let result = [];
                this.data_list.forEach((file) => {
                    if (file.is_select) {
                        result.push(file);
                    }
                })
                return result;
            },
            uploadData() {
                return {
                    group_id: this.now_group > 0 ? this.now_group : 0,
                    file_type: this.file_type,
                    acl: this.acl,
                    ...this.form_data
                }
            }
        },
        methods: {
            GetList() {
                this.httpGet("{:url('component/upload/file/lists')}", {
                    page: this.current_page,
                    file_type: this.file_type,
                    group_id: this.now_group,
                    acl: this.acl,
                }, true, '.el-dialog__body').then(res => {
                    if (res.status) {
                        let {lists = []} = res.data
                        this.handRes(lists)
                    }
                })
            },
            confirmEvent() {
                if (this.selected_file_list.length === 0) {
                    if (this.file_type === 'image') {
                        this.$message.error('请选择你需要的图片')
                    } else if (this.file_type === 'image') {
                        this.$message.error('请选择你需要的视频')
                    } else {
                        this.$message.error('请选择你需要的文件')
                    }
                    return
                }
                this.$emit('confirm', this.selected_file_list)
                this.$emit('close')
                //确认之后，选择列表清空
                this.clickCancelSelected()
            },
            moveFileGroup() {
                return this.httpPost("{:url('component/upload/file/move')}", {
                    selected_file_ids: this.selected_file_ids,
                    group_id: this.move_group_id
                }, true, '.el-dialog__body').then(res => {
                    if (res.status) {
                        this.$message.success(res.msg)
                        this.GetList()
                    }
                })
            },
            clickDeleteSelected() {
                this.$confirm('确认删除？', {
                    type: 'warning'
                }).then(() => {
                    // console.log('clickDeleteSelected', this.selected_file_ids)
                    return this.httpPost("{:url('component/upload/file/delete')}", {selected_file_ids: this.selected_file_ids})
                }, true, '.el-dialog__body').then(res => {
                    if (res.status) {
                        this.$message.success(res.msg)
                        this.GetList()
                    }
                }).catch(err => {
                })
            },
            clickCancelSelected() {
                let data_list = this.data_list
                for (var i = 0; i < data_list.length; i++) {
                    data_list[i].is_select = false
                }
                this.data_list = [...data_list]
            },
            selectFileEvent(index) {
                let data_list = this.data_list
                data_list[index]['is_select'] = !this.data_list[index].is_select
                this.data_list = [...data_list]
            },
            handleExceed() {
            },
            handleUploadChange() {
            },
            handleUploadError(e) {
                let message = e.message
                this.$loading(
                    {target: '.el-dialog__body'}
                ).close();
                if (this.upload_drive === 'qcloud') {
                    //获取腾讯云上传失败信息，返回错误内容
                    let reg = new RegExp('<Message>' + '(.*?)' + '</Message>');
                    message = message.match(reg)[1] || '上传请求错误，你留意你上传文件的大小、格式或配置信息。'
                }
                this.$message.error(message ? message : '上传请求错误，你留意你上传文件的大小或格式。')
            },
            httpRequestError(action, option, xhr) {
                let msg;
                if (xhr.response) {
                    msg = `${xhr.response.error || xhr.response}`;
                } else if (xhr.responseText) {
                    msg = `${xhr.responseText}`;
                } else {
                    msg = `fail to post ${action} ${xhr.status}`;
                }

                const err = new Error(msg);
                err.status = xhr.status;
                err.method = 'post';
                err.url = action;
                return err;
            },
            httpRequestGetHeader(xhr) {


                // console.log('xhr', xhr)
                // console.log('headerText', xhr.getResponseHeader('Location'))
                let headerText = xhr.getAllResponseHeaders()
                console.log('headerText', headerText)
                let headers = {}
                headerText.split(`\r\n`).forEach(item => {
                    let [k, v] = item.split(': ')
                    if (k) {
                        headers[k] = v
                    }
                })
                return headers
            },
            //重写上传事件
            httpRequestGetBody(xhr) {
                const text = xhr.responseText || xhr.response;
                if (!text) {
                    return text;
                }

                try {
                    return JSON.parse(text);
                } catch (e) {
                    return text;
                }
            },
            httpRequestEvent(option) {
                if (typeof XMLHttpRequest === 'undefined') {
                    return;
                }
                const xhr = new XMLHttpRequest();
                const action = option.action;
                if (xhr.upload) {
                    xhr.upload.onprogress = function progress(e) {
                        if (e.total > 0) {
                            e.percent = e.loaded / e.total * 100;
                        }
                        option.onProgress(e);
                    };
                }

                const formData = new FormData();
                if (this.upload_drive === 'qcloud') {
                    //如果是腾讯云上传，构建key
                    let ext = option.file.name.split('.').pop().toLowerCase()
                    let rand = Math.ceil(Math.random() * 1000000)
                    formData.append('key', new Date().getTime() + '' + rand + "." + ext)
                }
                if (option.data) {
                    Object.keys(option.data).forEach(key => {
                        formData.append(key, option.data[key]);
                    });
                }

                formData.append(option.filename, option.file, option.file.name);

                xhr.onerror = function error(e) {
                    option.onError(e);
                };

                xhr.onload = () => {


                    if (xhr.status < 200 || xhr.status >= 300) {
                        return option.onError(this.httpRequestError(action, option, xhr));
                    }
                    console.log( xhr.getAllResponseHeaders())
                    option.onSuccess({
                        body: this.httpRequestGetBody(xhr),
                        header: this.httpRequestGetHeader(xhr)
                    });
                };

                xhr.open('post', action, true);

                if (option.withCredentials && 'withCredentials' in xhr) {
                    xhr.withCredentials = true;
                }

                const headers = option.headers || {};

                for (let item in headers) {
                    if (headers.hasOwnProperty(item) && headers[item] !== null) {
                        xhr.setRequestHeader(item, headers[item]);
                    }
                }
                xhr.send(formData);
                return xhr;
            },
            handleUploadSuccess({body = '', header}, file) {
                //将请求的结果进行解密处理
                body = this.decryptRes(body)
                if (this.upload_drive === 'qcloud') {
                    //如果是腾讯云上传，获取返回结果header location
                    if (body === '') {
                        //上传成功，返回body为空
                        let file_url = header.location
                        let request_data = {
                            ...this.uploadData, file_url,
                            file_drive: this.upload_drive,
                            file_name: file.name,
                            file_size: file.size,
                            file_ext: file.name.split('.').pop().toLowerCase()
                        }
                        this.httpPost("{:url('component/upload/save')}", request_data).then(res => {
                            if (!res.status) {
                                this.$message.error(body.msg)
                            }
                        })
                    }
                } else {
                    this.$loading({target: '.el-dialog__body'}).close();
                    if (!body.status) {
                        this.$message.error(body.msg)
                    }
                }
            },
            uploadingClose() {
                this.show_uploading = false
                this.uploading_file_list = []
                this.GetList()
            },
            handleUploadProgress(e, file) {
                if (!this.show_uploading) {
                    this.show_uploading = true
                }
                let uploading_file = {}
                uploading_file[file.uid] = {
                    file_name: file.name,
                    file_uid: file.uid,
                    percent: parseFloat(e.percent.toFixed(2))
                }
                this.uploading_file_list = {
                    ...this.uploading_file_list,
                    ...uploading_file,
                }
            },
            beforeUploadEvent(file) {
                //上传之前校验格式和大小， 文件格式匹配不区分大小写
                let ext = file.name.split('.').pop().toLowerCase()
                let size = file.size
                let {upload_allow_ext = [], upload_file_size = 2048} = this.upload_setting
                if (upload_allow_ext && upload_allow_ext.length > 0) {
                    // 不区分大小写
                    let find = upload_allow_ext.findIndex(i => i.toLowerCase() === ext)
                    if (find === -1) {
                        this.$message.error('不允许上传文件格式 ' + ext)
                        return false
                    }
                }
                if (upload_file_size < (Math.ceil(size / 1024))) {
                    this.$message.error('超过上传限制 ' + upload_file_size + 'K')
                    return false
                }
                return true
            }
            ,
            selectGroup(group_id) {
                this.now_group = group_id
                this.current_page = 1
                this.GetList()
            }
            ,
            getGroupList() {
                this.httpGet("{:url('component/upload/group/lists')}", {
                    file_type: this.file_type,
                    acl: this.public_read ? 'public-read' : 'default'
                }, true, '.el-dialog__body').then(res => {
                    if (res.status) {
                        let {group_list = [], upload_form = {}, upload_drive = '', upload_setting = {}} = res.data
                        this.group_list = group_list
                        this.upload_drive = upload_drive
                        this.upload_setting = upload_setting
                        if (upload_drive === 'qcloud' && upload_form.post_url) {
                            this.upload_url = upload_form.post_url
                            this.form_data = upload_form.form_data
                            this.acl = upload_form.acl
                        }
                        this.GetList()
                    }
                })
            }
            ,
            handleGroup(c, {group_id, group_name}) {
                // console.log(c, {group_id, group_name})
                if (c === 'edit') {
                    this.editGroup(group_name, group_id)
                }
                if (c === 'delete') {
                    this.deleteGroup(group_id)
                }
            }
            ,
            deleteGroup(group_id) {
                this.$confirm('是否确认删除该分组？', '提示').then(() => {
                    return this.httpPost("{:url('component/upload/group/delete')}", {
                        group_id
                    })
                }, true, '.el-dialog__body').then(res => {
                    if (res.status) {
                        this.$message.success(res.msg);
                        this.getGroupList()
                    }
                }).catch(err => {
                })
            }
            ,
            editGroup(inputValue = '', group_id = 0) {
                var that = this;
                that.$prompt('请输入分组名称', (group_id > 0 ? '编辑' : '新增') + '分组', {
                    confirmButtonText: '保存',
                    cancelButtonText: '取消',
                    inputValue,
                    roundButton: true,
                    closeOnClickModal: false,
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            this.httpPost("{:url('component/upload/group')}", {
                                group_name: instance.inputValue,
                                file_type: this.file_type,
                                group_id
                            }, true, '.el-dialog__body').then(res => {
                                if (res.status) {
                                    this.$message.success(res.msg);
                                    this.getGroupList()
                                    done()
                                }
                            })
                        } else {
                            done()
                        }
                    }
                }).catch(err => {
                });
            }
            ,
        }
    }
</script>

<?php endif; ?>